package com.ruoyi.framework.aspectj;

import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.springframework.stereotype.Component;
import com.ruoyi.common.annotation.RateLimiter;
import com.ruoyi.common.enums.LimitType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;

/**
 * 限流处理
 *
 * @author ruoyi
 */
@Aspect
@Component
public class RateLimiterAspect
{
    private static final Logger log = LoggerFactory.getLogger(RateLimiterAspect.class);

    private final ConcurrentMap<String, CounterWindow> counters = new ConcurrentHashMap<>();

    private static final class CounterWindow
    {
        volatile long windowStartMillis;
        volatile int count;
    }

    @Before("@annotation(rateLimiter)")
    public void doBefore(JoinPoint point, RateLimiter rateLimiter) throws Throwable
    {
        int timeSeconds = rateLimiter.time();
        int maxCount = rateLimiter.count();

        String combineKey = getCombineKey(rateLimiter, point);
        long now = System.currentTimeMillis();
        long windowMs = timeSeconds * 1000L;

        CounterWindow cw = counters.computeIfAbsent(combineKey, k -> {
            CounterWindow w = new CounterWindow();
            w.windowStartMillis = now;
            w.count = 0;
            return w;
        });

        synchronized (cw)
        {
            if (now - cw.windowStartMillis >= windowMs)
            {
                cw.windowStartMillis = now;
                cw.count = 0;
            }
            cw.count++;
            if (cw.count > maxCount)
            {
                throw new ServiceException("访问过于频繁，请稍候再试");
            }
            log.info("限制请求'{}',当前请求'{}',缓存key'{}'", maxCount, cw.count, combineKey);
        }
    }

    public String getCombineKey(RateLimiter rateLimiter, JoinPoint point)
    {
        StringBuffer stringBuffer = new StringBuffer(rateLimiter.key());
        if (rateLimiter.limitType() == LimitType.IP)
        {
            stringBuffer.append(IpUtils.getIpAddr()).append("-");
        }
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        Class<?> targetClass = method.getDeclaringClass();
        stringBuffer.append(targetClass.getName()).append("-").append(method.getName());
        return stringBuffer.toString();
    }
}
